<template>
	<el-dialog v-model="state.dialogFormVisible" width="30%" :z-index="9" @close="cancelHandle">
		<template #header>
			<div class="custom-header">{{ state.isUpdateFlag ? '新增' : '编辑' }}</div>
		</template>
		<el-form ref="ruleFormRef" :model="state.form" :rules="rules">
			<el-form-item prop="changjiangDeltaName" label="文件名称" label-width="200px">
				<el-input v-model="state.form.changjiangDeltaName" placeholder="文件名称" />
			</el-form-item>

			<el-form-item label="上传文件(请上传word或Pdf)" label-width="200px" prop="uploadlist">
				<!-- <div>上传文件(请上传word或Pdf)</div> -->
				<div style="width: 90%">
					<el-upload
						ref="uploadRef"
						:action="uploadApi"
						:headers="uploadHeaders"
						:data="uploadData"
						accept=".pdf, .doc, .docx"
						:limit="1"
						:file-list="uploadShowList"
						:on-exceed="handleExceed"
						:on-preview="handleUploadFilePreview"
						:on-success="handleUploadFileSuccess"
						:on-error="handleUploadFileError"
						:on-remove="handleUploadfileRemove"
					>
						<el-button type="primary">上传</el-button>
						<!-- <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div> -->
					</el-upload>
				</div>
			</el-form-item>

			<!-- <el-form-item label="备注" label-width="120px">
				<el-input v-model="state.form.remark" type="textarea" :rows="5" placeholder="请输入备注"></el-input>
			</el-form-item> -->
		</el-form>

		<template #footer>
			<span class="dialog-footer">
				<!-- <el-button @click="sumbitHandle(ruleFormRef, false)">暂存</el-button> -->
				<el-button type="primary" @click="sumbitHandle(ruleFormRef, true)">提交</el-button>
				<el-button @click="cancelHandle"> 关闭 </el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script lang="ts" setup>
import { UploadFile } from '@/interface/declare'
import type { FormInstance, UploadProps, UploadRawFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref } from 'vue'

import { useDictionaryStore } from '@/store/modules/dictionary'
const dictionaryStore = useDictionaryStore()
const leibielist = dictionaryStore.getDictionaryByCode('T003')

import { cjsaveOrUpdateApi } from '@/api/Changjiangdelta'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()

import { filePreviewByName } from '@/api/sys/upload'

interface RuleForm {
	reportingUnit: String
	reportingDate: String
	reportingLink: String
	linkTel: String
	linkEmail: String
	groupStandardName: String
	groupStandardNumber: String
	issuedUnit: String
	releaseDate: String
	implementationDate: String
	firstEditorUnit: String
	standardType: String
}
const state = reactive({
	form: {
		changjiangDeltaName: '',
		changjiangDeltaFileId: null,
		remark: '',
		uploadlist: []
	},
	dialogFormVisible: false,
	isUpdateFlag: false,
	checkedList: [],
	// 审核画面需要的
	isAuditUpdate: false,
	statusList: []
})
const ruleFormRef = ref<FormInstance>()
const rules = reactive({
	changjiangDeltaName: [{ required: true, message: '请输入文件名称', trigger: 'blur' }],
	uploadlist: [{ required: true, message: '请上传文件', trigger: 'change' }]
})
const emit = defineEmits(['refreshDataList'])
// 附件上传
const uploadApi = `${import.meta.env.MODE === 'development' ? 'http://220.196.89.86:9173' : window.location.protocol + '//' + window.location.host}/JGBStandardWebApi/api/files/upload`
const uploadHeaders = {
	Authorization: userStore.token
}
const uploadData = {
	extCode: 'other',
	remark: '附件'
}
const uploadRef = ref()
const uploadList = ref<UploadFile[]>([])
const uploadShowList = ref<UploadRawFile[]>([])
const handleExceed: UploadProps['onExceed'] = files => {
	ElMessageBox.confirm('只能上传一份文件，若要替换，请先删除已有文件', '温馨提示', {
		showConfirmButton: false,
		cancelButtonText: '知道了',
		type: 'warning'
	})
}

const handleUploadFilePreview = (ruploadFile: any) => {
	if (ruploadFile.systemFileName) {
		filePreviewByName(ruploadFile.systemFileName).then(res => {
			window.open(res.data.url)
		})
	} else {
		filePreviewByName(ruploadFile?.response.data.systemFileName).then(res => {
			window.open(res.data.url)
		})
	}
}

const handleUploadFileSuccess = (res: any, uploadFile: UploadRawFile) => {
	if (res.code == '200') {
		uploadList.value = []
		uploadList.value.push(res.data)
		state.form.uploadlist = uploadList.value
	} else {
		handleUploadFileError(res, uploadFile)
	}
}

const handleUploadfileRemove = (file: UploadRawFile) => {
	uploadList.value = []
	state.form.uploadlist = []
}

const handleUploadFileError = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	uploadShowList.value = uploadShowList.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
	state.form.uploadlist = uploadShowList.value
}
// ==============================================================
const init = (isUpdate: any, row: any) => {
	state.isUpdateFlag = isUpdate
	if (!isUpdate) {
		detailMethods(row)
	}
	state.dialogFormVisible = true
}

const detailMethods = async (row: any) => {
	state.form['id'] = row.id
	state.form.changjiangDeltaName = row.changjiangDeltaName
	state.form.changjiangDeltaFileId = row.changjiangDeltaFileId
	state.form.remark = row.remark
	state.form.uploadlist = [row.file]
	const aa = {
		...row.file,
		name: row.file.fileName,
		systemFileName: row.file.systemFileName
	}
	state.form.uploadlist = [aa]
	uploadShowList.value = [aa]
	uploadList.value = [aa]
}
const sumbitHandle = async (formEl: FormInstance | undefined, isFlag: Boolean) => {
	if (!formEl) {
		return
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			state.form.changjiangDeltaFileId = uploadList.value[0] ? uploadList.value[0].id : ''

			// 判断是暂存还是提交
			submitRecord()
		} else {
			console.log('提交错误', fields)
		}
	})
}
//
const submitRecord = async () => {
	state.form['hasSubmit'] = true

	const aa = state.form as any
	delete aa.hasSubmit
	delete aa.uploadlist
	await cjsaveOrUpdateApi(aa).then(res => {
		ElMessage.success({
			message: '操作成功',
			duration: 500
		})
		cancelHandle()
	})
}

const cancelHandle = () => {
	ruleFormRef.value?.resetFields() // 表单验证关闭
	state.checkedList = []
	state.dialogFormVisible = false

	const aa = {
		changjiangDeltaName: '',
		changjiangDeltaFileId: null,
		remark: '',
		uploadlist: []
	}
	state.form = aa
	uploadList.value = []
	uploadShowList.value = []
	emit('refreshDataList')
}

defineExpose({
	init
})
</script>

<style scoped>
.dialog-footer {
	padding-bottom: 20px;
}
</style>
